package com.lzh.dlykserver.controller;

import com.github.pagehelper.PageInfo;
import com.lzh.dlykserver.entity.TActivity;
import com.lzh.dlykserver.query.ActivityQuery;
import com.lzh.dlykserver.result.R;
import com.lzh.dlykserver.service.ActivityService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

@RestController
public class ActivityController {

    @Resource
    private ActivityService activityService;


    /**
     * 市场活动分页
     * @param current
     * @return
     */
    @GetMapping("/api/activities")
    public R activityPage(@RequestParam(value = "current", required = false) Integer current,
                          ActivityQuery activityQuery) {
        if (current == null) {
            current = 1;
        }
        PageInfo<TActivity> pageInfo = activityService.getactivityByPage(current, activityQuery);
        return R.OK(pageInfo);
    }

    /**
     * 添加市场活动
     * @param activityQuery
     * @param token
     * @return
     */
    @PostMapping("/api/activity")
    public R addActivity(ActivityQuery activityQuery, @RequestHeader(value = "Authorization") String token) {
        activityQuery.setToken(token);
        int count = activityService.saveActivity(activityQuery);
        return count >= 1 ? R.OK() : R.FAIL();
    }

    /**
     * 获取市场活动信息
     * @param id
     * @return
     */
    @GetMapping("/api/activity/{id}")
    public R loadActivity(@PathVariable("id") Integer id) {
        TActivity tActivity = activityService.getActivityById(id);
        return R.OK(tActivity);
    }


    /**
     * 编辑市场活动信息
     * @param activityQuery
     * @param token
     * @return
     */
    @PutMapping("/api/activity")
    public R editActivity(ActivityQuery activityQuery, @RequestHeader(value = "Authorization") String token) {
        activityQuery.setToken(token);
        int update = activityService.updateActivity(activityQuery);
        return update >= 1 ? R.OK() : R.FAIL();
    }


    /**
     * 删除市场活动
     * @param id
     * @return
     */
    @DeleteMapping("/api/activity/{id}")
    public R deleteActivity(@PathVariable("id") Integer id) {
        int delete = activityService.deleteActivity(id);
        return delete >= 1 ? R.OK() : R.FAIL();
    }

    /**
     * 批量删除市场活动
     * @param ids
     * @return
     */
    @DeleteMapping("/api/activity")
    public R batchDeleteActivity(@RequestParam("ids") String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        int batchDel = activityService.batchDeleteActivity(idList);
        return batchDel >= idList.size() ? R.OK() : R.FAIL();
    }
}
